﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Mvc;
using AspNetMvc.Entities;
using AspNetMvc.Helpers;
using AspNetMvc.Models;
using CoreVirtuoso.Config;
using CoreVirtuoso.Descriptions;
using Infrastructure;
using Infrastructure.Events;
using Infrastructure.Events.Interfaces;
using Infrastructure.Pluralization;
using NGenerics.DataStructures;
using VDS.RDF;
using VirtuosoDal.Config;
using VirtuosoDal.Entities;
using VirtuosoDal.Repositories.RdfRepositories.Events;
using VirtuosoDal.Repositories.RdfRepositories.Interfaces.Events;
using WebGuiMvc.Helpers;
using WebGuiMvc.Helpers.Properties;

namespace AspNetMvc.Controllers
{
    public partial class SearchController : BaseController
    {
        private readonly IEventsContentRepository _eventsContentRepository;
        private readonly IEventsOntologyClassesService _eventsOntologyClassesService;

        public SearchController(IEventsContentRepository eventsContentRepository, IEventsOntologyClassesService eventsOntologyClassesService)
        {
            _eventsContentRepository = eventsContentRepository;
            _eventsOntologyClassesService = eventsOntologyClassesService;
        }

        public virtual ActionResult Index()
        {
            return View(Views.Index);
        }

        //
        // GET: /Search/Search

        public virtual ActionResult Search(string q, int? page)
        {
            if (page == null)
                page = 1;

            var intPage = (int) page;

            string textQuery = q;

            string geoObjectUri = Request.QueryString.Get("geoObjectsListBox");
            if (String.IsNullOrEmpty(geoObjectUri) || geoObjectUri == DummyItemsConfig.DummyItemValue)
                geoObjectUri = null;

            var resultSet = _eventsContentRepository.GetEventsForSearch(textQuery, geoObjectUri, Language, (int)page);

            var eventsForView = EventForViewHelper.Build(_eventsOntologyClassesService, resultSet, Language);
            var pagedResultSet = new PagedModel<List<EventForView>>(eventsForView, resultSet.TotalCount, intPage, PagingConfig.PageSize);

            //ToDo: Move it to ResultSet under ItemsPluralizedName property
            ViewData["Events"] = new EventWordPluralizationFactory().GetPluralizationStrategy(CultureInfo.CurrentCulture).Pluralize(
                pagedResultSet.ItemsCount);

            return View(Views.SearchResults, pagedResultSet);
        }
    }
}
